package com.lq.util;

import com.lq.pojo.Log;
import com.lq.pojo.LogContent;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 后台操作日志
 */

public class SystemLogUtil {

    private static Connection connection;
    private static PreparedStatement ps;
    private static ResultSet resultSet;

    private static void SaveLog(int logId){
        try {
            connection = new JdbcUtil().getConnection();

            String sql = "INSERT INTO t_log VALUES(null,?,null)";

            ps = connection.prepareStatement(sql);
            ps.setInt(1,logId);

            ps.executeUpdate();

            new JdbcUtil().closeAllResource(ps,connection);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取最新的前五条日志
    public static List<Log> getSystemLog(){
        int limit = 5;
        List<Log> logList = new ArrayList<>();

        try {
            connection = new JdbcUtil().getConnection();
            //以日志时间倒叙排列获取最新的日志
            String sql = "select log_id, log_content_id,log_time,content_id, log_content " +
                         "from t_log inner join t_log_content on log_content_id = content_id " +
                         "order by log_time desc limit ?";
            ps = connection.prepareStatement(sql);
            ps.setInt(1,limit);
            resultSet = ps.executeQuery();

            while (resultSet.next()) {
                Log log = new Log(
                        resultSet.getInt("log_id"),
                        resultSet.getInt("log_content_id"),
                        resultSet.getTimestamp("log_time"),
                        new LogContent(
                                resultSet.getInt("content_id"),
                                resultSet.getString("log_content")
                        )
                );
                logList.add(log);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return logList;
    }

    //登陆后台log
    public static void loginBackLog(){
        SaveLog(1);
    }

    //删除评论log
    public static void deleteCommentLog(){
        SaveLog(2);
    }

    //编辑文章log
    public static void editArticleLog(){
        SaveLog(3);
    }

    //删除文章log
    public static void deleteArticleLog(){
        SaveLog(4);
    }

    //修改设置log
    public static void editSettingLog(){
        SaveLog(5);
    }

    //发布文章log
    public static void publishArticleLog(){
        SaveLog(6);
    }

    //删除文件log
    public static void deleteDocumentLog(){
        SaveLog(7);
    }
}
